package com.crm.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.exception.FastDFSException;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.FileUtil;
import com.crm.common.util.PathUtil;
import com.crm.common.util.fastdfs.FastDFSClient;
import com.crm.model.entity.sys.FileUpload;
import com.crm.service.common.FileUploadDbService;
import com.crm.system.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author luojie
 * @date 2020/12/21 16:25
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    FileUploadDbService fileUploadDbService;

    private FastDFSClient fastDFSClient = new FastDFSClient();

    /***
     * @Description:公告上传文件方法
     * @Param: multipartFile 文件
     * @Param: businessPath 业务路径
     * @Author: luojie
     * @Date: 2021/4/20 16:35
     */
    public FileUpload uploadFile(MultipartFile multipartFile,Boolean ifSavePdf) throws FastDFSException {
        //判断文件是否为空
        if(multipartFile!=null){

            String fileName = multipartFile.getOriginalFilename();//原文件名
            String fileType = FilenameUtils.getExtension(fileName).toLowerCase();//文件类型
/*          String filePath = FileUtil.generateFilePath(time,fileName, businessPath);
            long time = System.currentTimeMillis();
            File file = new File(filePath);
            //上传文件
            multipartFile.transferTo(file);

            String crmIp = PathUtil.getCrmIp();//IP
            String port = PathUtil.getPort();//端口
            String accessPath = PathUtil.getAccessPath();
            String accessUrl="http://" + crmIp + ":" + port + accessPath + businessPath + time + fileName;//本地运行项目
            // 1: 文件表(sys_file_upload)新增
            String fileId = insertFileUpload(fileName,filePath,accessUrl,fileType);*/
            String fileSaveUrl = fastDFSClient.uploadFileWithMultipart(multipartFile);
            String accessUrl = "https://fastdfs.dcrm.cn/"+fileSaveUrl;
            String fileId = insertFileUpload(fileName,fileSaveUrl,accessUrl,fileType);

            //如果文件为word则另存word文件为pdf格式（前端返回pdf文件的绝对路径，下载时使用word文件的绝对路径）
/*            if(ifSavePdf&&(fileName.endsWith("docx")||fileName.endsWith("doc"))){
                String filePdfName = fileName.substring(0,fileName.lastIndexOf("."))+".pdf";
                String filePdfPath = FileUtil.generateFilePath(time,filePdfName, businessPath);
                FileUtil.doc2pdf(filePath,filePdfPath);
            }*/

            FileUpload fileUpload = new FileUpload();
            //拼凑返回值
            if(!StringUtils.isBlank(fileId)){
                fileUpload.setUploadId(fileId);
                fileUpload.setAccessUrl(accessUrl);
                fileUpload.setFileName(fileName);
                fileUpload.setFilePath(fileSaveUrl);
            }
            return fileUpload;
        }else {
            return null;
        }
    }


    @Override
    public String insertFileUpload(String fileName,String filePathStr,String accessUrl,String contentType) {
        String id = UUID.randomUUID().toString().replaceAll("-","");
        FileUpload fileUpload = new FileUpload();
        fileUpload.setUploadId(id);
        fileUpload.setAccessUrl(accessUrl);
        fileUpload.setFilePath(filePathStr);
        fileUpload.setFileName(fileName);
        fileUpload.setFileType(contentType);
        fileUpload.setCreateTm(new Date());
        fileUpload.setUpdateTm(new Date());
        fileUpload.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
        Boolean result = fileUploadDbService.insertFileUpload(fileUpload);
        if(result){
            return id;
        }else{
            return "";
        }

    }

    @Override
    public FileUpload selectFileUploadById(String id) {
        FileUpload fileUpload = fileUploadDbService.selectFileUploadById(id);
        return fileUpload;
    }

    @Override
    public Boolean deleteFileUploadById(String id) {
        Boolean result = fileUploadDbService.deleteFileUploadById(id);
        return result;
    }

}
